﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

using Atosenet.PluginEngine;


namespace Atosenet.IO
{
    [PluginAttribute("Atosenet", "Atosenet.IO.ManualIO", "模拟连接", PluginType.IO)]
    public class ManualIO : BaseIO
    {
        #region 初始化

        public ManualIO()
            : base(ManualIOParameter.Default)
        { }

        public ManualIO(ManualIOParameter param)
            : base(param)
        { }

        #endregion


        #region 公开函数

        public override bool ApplyParameter()
        {
            return true;
        }

        public override bool Open()
        {
            OnIOOpened();
            return true;
        }

        public override bool Close()
        {
            OnIOClosed();
            return true;
        }

        public override bool Close(int id)
        {
            if (id == ID)
                return Close();

            return false;
        }

        public override int WriteTo(int id, byte[] buffer, int offset, int length)
        {
            if (id == ID)
                return Write(buffer, offset, length);

            return -1;
        }

        public override int Write(byte[] buffer, int offset, int length)
        {
            try
            {
                byte[] data = new byte[length];
                Array.Copy(buffer, offset, data, 0, length);
                OnRawDataReceived(data);
                return length;
            }
            catch
            {
                OnRawDataReceived(IOErrorType.WriteError);
                return -1;
            }
        }

        #endregion


        #region 静态函数

        public static ManualIO CreateInstance(ManualIOParameter param)
        {
            ManualIO io = new ManualIO(param);
            return io;
        }

        public static ManualIO CreateInstance()
        {
            ManualIO io = new ManualIO();
            return io;
        }

        #endregion


        #region 属性

        public new ManualIOParameter IOParam
        {
            get { return base.IOParam as ManualIOParameter; }
        }

        #endregion
    }
}
